package test;

import jdk.internal.util.xml.impl.Input;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoServer {
    private ServerSocket socket = null;
    public TcpEchoServer(int port) throws IOException {
        socket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器上线！");
        while(true){
            Socket clientSocket = socket.accept();
            Thread t = new Thread(()->{
                try {
                    processClient(clientSocket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            t.start();
        }
    }

    private void processClient(Socket clientSocket) throws IOException {
        System.out.printf("客户端上线 [%s,%d]",clientSocket.getInetAddress(),clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            Scanner scanner = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while(true){
                if(!scanner.hasNext()){
                    break;
                }
                String requet = scanner.next();
                String response = process(requet);
                printWriter.println(response);
                printWriter.flush();
                System.out.printf("[%s,%d],req=%s,resp=%s",clientSocket.getInetAddress(),clientSocket.getPort(),
                        requet,response);
            }
        }catch(IOException e){
            e.printStackTrace();
        }finally {
            clientSocket.close();
            System.out.println("客户端下线");
        }
    }

    private String process(String requet) {
        return requet;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer t = new TcpEchoServer(9090);
        t.start();
    }
}
